import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
// components
import ChatRoom from "./chat-room/chat-room"
import Index from "./index"
import Analysis from "./analysis/analysis"
import Vip from "./vip/vip"
import Live from "./live/live";
import Plan from "./plan/plan";
import GameRoomTab from "./GameRoomTab/GameRoomTab";
// style sheet
import './Main.css'

import LocalStorageService from "../../../../utils/LocalStorageService";
import Lineup from "./lineup/lineup";
import {bindEvent, getDom, getDoms,} from "../../../../utils/commonfunc";
import _ from "lodash";
import {behaviorReq, getHasPlanReq} from "../../../../apis/goApis";
import Together from "./together/together";
import {log} from "../../../../utils/commonfunc";
import VipRoom from "./vip-room/vip-room";

class GameRoomTabs extends React.Component {
    constructor(props) {
        super(props)
        this.state={
            // page: this.getInitialPage(),
            contentCtn: null,
            tabs: [],
        }
    }


    componentDidUpdate(prevProps, prevState, snapshot) {
        const last = prevProps.game
        const cur = this.props.game
        if (cur.matchId && cur.matchId !== last.matchId) {

            this.getHasPlan({
                    Namiid: parseInt(cur.matchId),
                    Name: cur.matchevent.name_zh,
                })
                .then((resp) => {
                    return resp.data.ok === 1
                    // this.setTabs(hasPlan)
                })
                .then(hasPlan => {
                    this.setTabs(hasPlan)
                })
                .then(() => {
                    if (this.props.game.info.statusid === 1) {
                        const page = this.state.tabs.findIndex(t => t.title === '数据')
                        this.setState({
                            page: page,
                        })
                    }
                })
        }
    }

    getHasPlan(params) {
        const req = getHasPlanReq(params)
        return req
    }

    setTabs(hasPlan) {
        const hasPlanTabs = [
            {title: '直播', active: true,},
            // {title: 'VIP包厢', active: false,},
            {title: '一起看', active: false,},
            {title: '阵容', active: false,},
            {title: '推荐', active: false,},
            {title: '数据', active: false,},
            {title: '指数', active: false,},
        ]
        const notPlanTabs = [
            {title: '直播', active: true,},
            // {title: 'VIP包厢', active: false,},
            {title: '一起看', active: false,},
            {title: '阵容', active: false,},
            {title: '数据', active: false,},
            {title: '指数', active: false,},
        ]
        this.setState({
            tabs: hasPlan ? hasPlanTabs : notPlanTabs,
        }, () => {
            // this.setPage()
        })
    }
    setPage() {
        const tabs = this.state.tabs
        const page = tabs.findIndex(t => t.title === '一起看')
        this.setState({
            page,
        })
    }

    bindScrollEvent = (bottomCallback = () => {}) => {
        // let ctn = getDom('.am-tabs-pane-wrap-active')
        const ctnList = getDoms('.am-tabs-pane-wrap-active')
        const ctn = ctnList[ctnList.length - 1]
        const scrollCallback = _.throttle(() => {
            const content = this.state.contentCtn

            if (content) {

                const contentHeight = content.scrollHeight
                const afterScrollHeight = document.documentElement.clientHeight - 64 - 43.5
                const top = ctn.scrollTop
                const reachBottom = top === contentHeight - ctn.clientHeight

                if (top > 0 && afterScrollHeight < contentHeight) {
                    this.props.setAtTop(false)
                }
                if (top === 0) {
                    this.props.setAtTop(true)
                }
                if (reachBottom) {
                    bottomCallback()
                }
            }
        }, 100)
        if (ctn) {
            bindEvent(ctn, 'scroll', scrollCallback)
        }
    }

    setContentCtn = (dom, callback) => {
        this.setState({
            contentCtn: dom,
        }, callback())
    }

    checkTabClick = (e, i) => {
        this.props.setAtTop(true)
        // const storage = LocalStorageService
        // let isLogin = storage.get('isLogin')
        // const props = this.props
        // if (isLogin) {
        // } else {
        //     props.history.push('../login')
        // }
        this.setState({
            page: i,
        })

    }

    onTabChange = (e, i) => {
        this.setState({
            page: i,
        })
        this.props.setAtTop(true)
    }

    changePage = (i) => {
        this.setState({
            page: i,
        })
    }

    // getInitialPage = () =>　{
    //     const storage = LocalStorageService
    //     let isLogin = storage.get('isLogin')
    //     const props = this.props
    //     let initialPage
    //
    //     if (isLogin) {
    //         try {
    //             const {
    //                 location: {
    //                     state: {
    //                         status,
    //                         AIBtnClick,
    //                     }
    //                 },
    //             } = props
    //             const statusId = status
    //             const isStarted = statusId >= 2 && statusId <= 7
    //             const isFinished = statusId === 8
    //
    //             if (AIBtnClick) {
    //                 initialPage = 2
    //             } else {
    //                 if (isStarted || isFinished || statusId === 999) {
    //                     initialPage = 0
    //                 } else if (statusId === 1) {
    //                     initialPage = 3
    //                 }
    //             }
    //         } catch (e) {
    //             initialPage = 0
    //         }
    //
    //     } else if (!isLogin) {
    //         initialPage = 0
    //     }
    //
    //     const search = props.location.search
    //     if (search.length > 0) {
    //         let obj = {}
    //         search
    //             .slice(1)
    //             .split('&')
    //             .map(kv => {
    //                 const arr = kv.split('=')
    //                 const key = arr[0]
    //                 const val = arr[1]
    //                 obj[key] = val
    //             })
    //         const style = Number(obj.style)
    //         if (isNaN(style)) {
    //             initialPage = 0
    //         } else if (style <= 6) {
    //             initialPage = 1
    //         } else if (style === 101) {
    //             initialPage = 2
    //         } else if (style === 100) {
    //             initialPage = 4
    //         }
    //
    //     }
    //     return initialPage
    // }

    render() {
        const storage = LocalStorageService
        let isLogin = storage.get('isLogin')
        const props = this.props

        // const initialPage = this.getInitialPage()


        const location = props.location
        const locationState = location.state
        const AIBtnClick = locationState && location.state.AIBtnClick
            ? location.state.AIBtnClick
            : false


        const atTop = this.props.atTop
        const downloadShow = this.props.downloadShow
        const isOnScroll = this.props.onScrollEvent

        const normalCls = atTop
            ? 'game-room-main-container'
            : isOnScroll
                ? 'game-room-main-container game-room-main-container-full'
                : 'game-room-main-container'
        const downloadCls = atTop
            ? 'game-room-main-container-d'
            : isOnScroll
                ? 'game-room-main-container-d game-room-main-container-full-d'
                : 'game-room-main-container-d'
        let ctnCls = downloadShow
            ? downloadCls
            : normalCls

        const MainTemplate = this.state.tabs.length > 0 && (
            <div
                className={ctnCls}
                // className='game-room-main-container'
            >
                <GameRoomTab
                    tabs={this.state.tabs}
                    prerenderingSiblingsNumber={0}
                    animated={false}
                    // destroyInactiveTab={true}
                    // initialPage={initialPage}
                    // initialPage={4}
                    onTabClick={(e, i) => {this.checkTabClick(e, i)}}
                    tabBarUnderlineStyle={{background: '#36C8B9',}}
                    onChange={(e, i) => this.onTabChange(e, i)}
                    page={this.state.page}
                >
                    {this.state.tabs.map(tab => {

                        const mapper = {
                            '直播': <Live
                                bindScrollEvent={this.bindScrollEvent}
                                setContentCtn={this.setContentCtn}
                                containers={this.props.containers}
                                setAtTop={this.props.setAtTop}
                                cancelOnScroll={this.props.cancelOnScroll}
                                onScrollEvent={this.props.onScrollEvent}
                            />,
                            '阵容': <Lineup
                                bindScrollEvent={this.bindScrollEvent}
                                setContentCtn={this.setContentCtn}
                                containers={this.props.containers}
                                setAtTop={this.props.setAtTop}
                                cancelOnScroll={this.props.cancelOnScroll}
                                onScrollEvent={this.props.onScrollEvent}
                            />,
                            '推荐': <Plan
                                bindScrollEvent={this.bindScrollEvent}
                                setContentCtn={this.setContentCtn}
                            />,
                            '聊天': <ChatRoom
                                type='game'
                                giftNotice
                                goalNotice
                                setScrollCtn={this.props.setScrollCtn}
                                containers={this.props.containers}
                                setAtTop={this.props.setAtTop}
                                chatFlag={0}
                            />,
                            '一起看': <Together
                                type='game'
                                giftNotice
                                goalNotice
                                setScrollCtn={this.props.setScrollCtn}
                                containers={this.props.containers}
                                setAtTop={this.props.setAtTop}
                                chatFlag={0}
                                curPage={this.state.page}
                                tabs={this.state.tabs}
                            />,
                            '数据': <Analysis
                                bindScrollEvent={this.bindScrollEvent}
                                setContentCtn={this.setContentCtn}
                                containers={this.props.containers}
                                setAtTop={this.props.setAtTop}
                                changePage={this.changePage}
                                cancelOnScroll={this.props.cancelOnScroll}
                                onScrollEvent={this.props.onScrollEvent}
                            />,
                            '指数': <Index
                                bindScrollEvent={this.bindScrollEvent}
                                setContentCtn={this.setContentCtn}
                            />,
                            'VIP包厢': <VipRoom />
                        }

                        return <React.Fragment key={tab.title}>
                            {mapper[tab.title]}
                        </React.Fragment>
                    })}
                </GameRoomTab>
            </div>

        )

        return MainTemplate
    }
}



const mapState = state => ({
    game: state.game.currentGame,
})

export default connect(mapState)(withRouter(GameRoomTabs))
